package com.zzs.server.service.impl;

import com.zzs.common.core.enums.ResponseCode;
import com.zzs.common.core.util.SnowflakeUtil;
import com.zzs.common.security.exception.ServiceException;
import com.zzs.server.dao.mysql.TestCaseMapper;
import com.zzs.common.core.entity.mysql.TestCaseDO;
import com.zzs.server.pojo.bo.test.SaveTestCaseBO;
import com.zzs.server.pojo.bo.test.UpdateTestCaseBO;
import com.zzs.server.pojo.vo.TestCaseVO;
import com.zzs.server.service.ProblemService;
import com.zzs.server.service.TestCaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zzs
 * @date 2025/03/18
 */
@Service
public class TestCaseServiceImpl implements TestCaseService {
    @Autowired
    private TestCaseMapper testCaseMapper;
    @Autowired
    private ProblemService problemService;

    @Override
    public void saveTestCase(SaveTestCaseBO saveTestCaseBO) {
        problemService.checkExistsAndPublish(saveTestCaseBO.getProblemId());
        TestCaseDO testCaseDO = new TestCaseDO();
        BeanUtils.copyProperties(saveTestCaseBO, testCaseDO);
        testCaseDO.setId(SnowflakeUtil.nextId());
        int effectRows = testCaseMapper.save(testCaseDO);
        if (effectRows != 1) {
            throw new ServiceException(ResponseCode.RESOURCE_CONFLICT);
        }
    }

    @Override
    public void updateTestCase(UpdateTestCaseBO updateTestCaseBO) {
        problemService.checkExistsAndPublish(updateTestCaseBO.getProblemId());
        TestCaseDO testCaseDO = new TestCaseDO();
        BeanUtils.copyProperties(updateTestCaseBO, testCaseDO);
        int effectRows = testCaseMapper.update(testCaseDO);
        if (effectRows != 1) {
            throw new ServiceException(ResponseCode.NOT_FOUND, "测试用例不存在");
        }
    }

    @Override
    public TestCaseVO getTestCase(long problemId) {
        TestCaseDO testCaseDO = testCaseMapper.get(problemId);
        if (testCaseDO == null) {
            throw new ServiceException(ResponseCode.NOT_FOUND, "测试用例不存在");
        }
        TestCaseVO testCaseVO = new TestCaseVO();
        BeanUtils.copyProperties(testCaseDO, testCaseVO);
        return testCaseVO;
    }

    @Override
    public void removeTestCase(long problemId) {
        problemService.checkExistsAndPublish(problemId);
        int effectRows = testCaseMapper.remove(problemId);
        if (effectRows != 1) {
            throw new ServiceException(ResponseCode.NOT_FOUND, "测试用例不存在");
        }
    }
}
